package com.nstskj.study.netty.tcp.netty.init;

import com.nstskj.study.netty.tcp.netty.channel.decoder.NetTcpMessageDecoder;
import com.nstskj.study.netty.tcp.netty.channel.encoder.NetTcpMessageEncoder;
import com.nstskj.study.netty.tcp.netty.channel.handler.NetMessageTcpServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project study-netty-iot
 * @date 2021/4/14 16:49
 * @Description 管道初始化
 */
public class NetProtoMessageTcpServerChannelInitializer extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
        ChannelPipeline channelPipLine = nioSocketChannel.pipeline();
        int maxLength = 256;
        //固定长度帧编码
        //最大包长度不限制，长度字段偏移2字节，长度域长度为4字节， 长度域不跳过字节即直接为数据域长度不添加长度填充 ， 初始化跳过的字节为0
        channelPipLine.addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0));
        channelPipLine.addLast("encoder", new NetTcpMessageEncoder());
        channelPipLine.addLast("decoder", new NetTcpMessageDecoder());
        //读写空闲
        channelPipLine.addLast("idle", new IdleStateHandler(0, 0, 5, TimeUnit.MINUTES));
        channelPipLine.addLast("handler", new NetMessageTcpServerHandler());
    }
}
